package com.freeseed.model.service.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.freeseed.model.entity.Role;
import com.freeseed.model.entity.User;
import com.freeseed.model.mapper.RoleMapper;
import com.freeseed.model.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class AuthUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_email",username));
        if(user == null){
            throw new UsernameNotFoundException(String.format("%s.这个用户不存在", username));
        }else {
            Role role = roleMapper.selectById(user.getRoleId());
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(role.getRoleDesc()));
            log.info("loadUserByUsername......user ===> {}",user);
            log.info(user.getUserPassword());
            AuthUser authUser = new AuthUser(user.getUserEmail(),user.getUserPassword(),user.getUserId(),authorities);
            log.info("AuthUser: {}",authUser);
            return authUser;
        }
    }
}
